<?php

/*

 $data = array(
 	"selected_value" : "yourValue",					// optional
	"list" : array(
        array( 
			"content" 	: "yourContent",
			"value" 	: "yourValue"				// optional:						 
		),
		...
    )
 )
 
 */

class spCombobox extends spSelect
{
	public function __construct( $param=null )
	{
		parent::__construct( $param );
		parent::setClass( "spCombobox" );

		if ( isset($param["list"]) )
			$this->addItems( $param["list"], isset($param["selected_value"])?$param["selected_value"]:"" );
			
		if ( isset($param["csv"]) )
			$this->addCSV( $param["csv"] );
	}
	
	public function addCSV( $csv )
	{
		if ( $csv=="" )
			return;
	
		$ar = explode( ",", $csv );
		foreach ($ar as $a )
		{
			$a = trim( $a );
		
			$option = new spOption(array("value"=>$a, "content"=>$a));
			parent::addChild( $option );
		}	
	}

	/*
	 * list : array(
	 *		array( "value"=>"yourValue1", "content"=>"yourContent1" ),
	 *		array( "value"=>"yourValue2", "content"=>"yourContent2" ),
	 *		array( "value"=>"yourValue3", "content"=>"yourContent3" )
	 * )
	 *  
	 */
	
	public function addItems( $list, $selected_value=false )
	{
		foreach ( $list as $item )
		{
			$option = new spOption( $item );
			
			if ( isset($item["value"]) )
			{
				if ( $selected_value && $item["value"]==$selected_value )
					$option->addAttr( "selected", "selected" );
			}
			
			parent::addChild( $option );
		}
	}
	
	public function setSelected( $value )
	{
		foreach ( parent::getChildrenArray() as $option )
		{
			if ( $option->getValue()==$value )
				$option->setSelected( true );
		}
	}
	
	public function setElementDataString( $s )
	{
		parent::setElementDataString( $s );	
		
		$this->setSelected( $s );
		
		/*
		foreach ( parent::getChildrenArray() as $option )
		{
			if ( $option->getValue()==$s )
				$option->setSelected( true );
		}
		*/
	}
	
	public function updateFromRequest()
	{
		parent::updateFromRequest();
		
		// convience variables
		$data = parent::getData();
		$r = $_REQUEST;	

		$selected_value = $r[$data["name"]];		
		
		$this->setElementDataString( $selected_value  );
	}			
}

?>